import React, {memo, MouseEvent, useState, Dispatch, useEffect, useCallback} from 'react';
import { useParams } from "react-router-dom";
import { isDevelopment, assign, getStore, setStore, removeStore } from '@bastet/utils';
import { IComponentType } from '@bastet/widgets';
import type { IComponent } from '@bastet/widgets';
import { BuilderInformation, BuilderWidgetPanel, BuilderEditor, useStateReducer, Context } from '../../../builder';
import { useMaterial, useWidgets, useSyncCallback } from '../../../hooks';


function getInformation (state: any, path?: string) {
  if (path) {
    const pathArr = path.split('-');
    let data = null;
    while (pathArr.length) {
      const path: string = pathArr.shift() as string
      if (!data) {
        data = state[path]
      } else {
        data = data[path]
      }
    }
    console.log('getInformation => ', data, path)
    return data;
  }
}

// console.log(originalState)
export default memo(() => {
  const [debugging, setDebugging ] = useState<any>(getStore('debugging'))
  const params = useParams<{id: string}>();
  const [ state, dispatch, changeField ] = useStateReducer()
  const [material, getMaterial, updateMaterial] = useMaterial()
  const widgets = useWidgets(debugging)
  const [ activated, setActivePath ] = useState<string>()
  // const [ information, setInformation ] = useInformationReducer<IComponent>(state as IComponent[])
  const information = getInformation(state as IComponent[], activated)
  const __onClick = (_event: MouseEvent <Element>, data: IComponent) => {
    console.log('BuilderLayout: ——————————————__onClick => ', data, information?.path)
    setActivePath(data.id)
  }

  useEffect(() => {
    if (params.id) {
      getMaterial(params.id, !!debugging).then(() => {
        console.log(`material: => `, material);
        // dispatch(res.widgets)
      })
    }

    // const remoteWidgets = debugWidgets(widgets, debugging)
    // const sceneWidgets = mergeWidget(scene.data.widgets, remoteWidgets)
    // console.log('sceneWidgets', scene.data.widgets, sceneWidgets)
    // dispatch(sceneWidgets)
  }, [debugging, params.id])

  useEffect(() => {
    // const remoteWidgets = debugWidgets(widgets, debugging)
    // const sceneWidgets = mergeWidget(scene.data.widgets, remoteWidgets)
    // console.log('sceneWidgets', scene.data.widgets, sceneWidgets)
    // dispatch(sceneWidgets)
    console.log(';;;;;;;;;;;;; => ', (import.meta as any).env.DEV, `debugging: => ${ debugging }`);
    console.log(`%cinit page data: => `, 'background: #8ce196;', { activated, information, material, state, widgets}, [...state.values()]);
  }, [debugging])

  const onSave = useSyncCallback(() => {
    console.log(`onSave: => `, state);
    if (state) {
      updateMaterial(state)
    }
  })

  const onCancel = () => {

  }
  const onDevelop = () => {
    if (debugging) {
      removeStore('debugging')
      setDebugging('')
    } else {
      setDebugging('debug')
      setStore('debugging', 'debug')
    }
  }

  console.log('material: => ', material)
  return (
      <div className="root-builder">
        <BuilderWidgetPanel widgets={widgets} />
        <Context.Provider value={debugging}>
          {
            material?.widgets && (
              <BuilderEditor
                defaultStyle={{ width: `calc(100vw - ${!information?.path ? 100 : 420}px)` }}
                state={material?.widgets}
                activated={activated}
                dispatch={dispatch as Dispatch<any>}
                widgets={widgets}
                onClick={__onClick}
                onSave={onSave}
                onCancel={onCancel}
                onDevelop={onDevelop}
              />
            )
          }

        </Context.Provider >
        {
            information?.path && (
                <BuilderInformation
                    information={information}
                    dispatch={changeField as Dispatch<any>}/>
            )
        }
      </div>
  )
})
